<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>WebSocket Chat</title>
    <script src="https://cdn.jsdelivr.net/npm/sockjs-client@1.5.1/dist/sockjs.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/stompjs@2.3.3/lib/stomp.min.js"></script>
</head>
<body>
<div id="chat">
    <input type="text" id="messageInput" placeholder="Type a message...">
    <button onclick="sendMessage()">Send</button>
    <div id="messages"></div>
</div>

<script>
    let stompClient = null;

    function connect() {
        const socket = new SockJS('/chat');
        stompClient = Stomp.over(socket);
        stompClient.connect({}, function () {
            // 订阅消息
            stompClient.subscribe('/topic/messages', function (message) {
                showMessage(JSON.parse(message.body));
            });
        });
    }

    function sendMessage() {
        const messageContent = document.getElementById("messageInput").value;
        if (messageContent && stompClient) {
            stompClient.send("/app/sendMessage", {}, JSON.stringify({
                sender: "User",
                content: messageContent
            }));
            document.getElementById("messageInput").value = "";
        }
    }

    function showMessage(message) {
        const messagesDiv = document.getElementById("messages");
        const messageElement = document.createElement("p");
        messageElement.textContent = message.sender + ": " + message.content;
        messagesDiv.appendChild(messageElement);
    }

    connect(); // 页面加载时连接
</script>
</body>
</html>
